package com.fly.graphql_demo.business.user.service

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.IService
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.fly.graphql_demo.business.user.data.User
import com.fly.graphql_demo.business.user.data.UserList
import com.fly.graphql_demo.business.user.data.UserMapper
import com.fly.graphql_demo.business.user.data.UserParam
import org.springframework.stereotype.Service
import java.util.*

interface UserService: IService<User> {

    fun saveUser(userParam: UserParam): User

    fun updateUser(userParam: UserParam): User?

    fun deleteUser(id: Int): Boolean

    fun queryId(id: Int): User

    fun queryUserList(): UserList

}

@Service
class UserServiceImp : ServiceImpl<UserMapper, User>(), UserService {

    override fun saveUser(userParam: UserParam): User = User().apply {
        name = userParam.name
        age = userParam.age
        email= userParam.email
        birthday = Date()
    }.run {
        save(this)
        this
    }

    override fun updateUser(userParam: UserParam): User? = getById(userParam.id)?.apply {
        name = userParam.name
        age = userParam.age
        email= userParam.email
        birthday = Date()
    }.run {
        save(this)
        this
    }

    override fun deleteUser(id: Int): Boolean = removeById(id)

    override fun queryId(id: Int): User = getById(id)

    override fun queryUserList(): UserList = UserList().apply {
        list(KtQueryWrapper(User::class.java).orderByDesc(User::birthday))
            ?.takeIf { it.isNotEmpty() }
            ?.run {
                users = this
                total = 0
            }
    }
}